#include <Arduino.h>
#include <PubSubClient.h>
#include <ESP8266WiFi.h>
// put function declarations here:
// mqtt 相关配置信息
const char *mqtt_broker_add = "bemfa.com"; //服务器地址
const uint16_t mqtt_broker_port = 9501; //服务端口
const char *mqtt_username = ""; // 账号
const char *mqtt_password = ""; //密码
const uint16_t mqtt_client_buff_size = 4096; //客服端缓存大小 非必须
String mqtt_client_id  = "80a28073cf4ab7febfa9664e4faed765"; //客户端id

const char *mqtt_topic_temp_pub = "temp004/set"; //需要发布到的主题
const char *mqtt_topic_switch_sub = "switch006"; //需要订阅switch主题
const char *mqtt_topic_led_sub = "led006"; // 订阅led灯主题

WiFiClient tcpClient;
PubSubClient mqttClient;

unsigned long previousConnectMillis = 0 ; //毫秒时间记录
const long intervalConnectMillis = 5000; // 时间间隔
unsigned long previousPublishMillis = 0; // 毫秒时间记录
const long intervalPublishMillis = 5000; //时间间隔

void mqtt_callback(char *topic, byte *payload, unsigned int length) {
  // 使用字符串比较来处理不同的主题
  if (strcmp(topic, "switch006") == 0) {
    Serial.print("switch006");
  } else if (strcmp(topic, "led006") == 0) {
    Serial.print("led006");
  }
  // 打印接收到的消息
  Serial.printf("Message arrived in topic %s, length %d\n", topic, length);
  Serial.print("Message: ");
  for (int i = 0; i < length; i++) {
    Serial.print((char)payload[i]);
  }
  Serial.println(); // 添加换行符以便于阅读
}

void reconnect() {
  while (!mqttClient.connected()) {
    Serial.print("Attempting MQTT connection....");
    if (mqttClient.connect(mqtt_client_id.c_str(), mqtt_username, mqtt_password)) {
      Serial.println("connected");
      mqttClient.subscribe(mqtt_topic_led_sub);
      mqttClient.subscribe(mqtt_topic_switch_sub);
    } else {
      Serial.print("failed rc =");
      Serial.print(mqttClient.state());
      Serial.println("type again in 5 seconds");
      delay(5000);
    }
  }
}

void setup() {
  // put your setup code here, to run once:
  Serial.begin(115200);
  // 设置mqtt客服端
  mqttClient.setClient(tcpClient);
  mqttClient.setServer(mqtt_broker_add, mqtt_broker_port);
  mqttClient.setBufferSize(mqtt_client_buff_size);
  mqttClient.setCallback(mqtt_callback);

   // 连接 WiFi
  WiFi.begin("your_ssid", "your_password");
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("WiFi connected");

}

void loop() {
  // put your main code here, to run repeatedly:
  if (!mqttClient.connected()) {
    reconnect();
  }

  unsigned long currentMillis = millis(); // 读取当前时间
  if (!mqttClient.connected()) {
    if (currentMillis - previousConnectMillis > intervalPublishMillis) {
      previousPublishMillis = currentMillis;
      mqttClient.publish(mqtt_topic_temp_pub, "naisu 233~~~~");
    }
  }
  mqttClient.loop();
}


